package com.dkd.applet.handler;

import cn.elegent.ac.ACHandler;
import cn.elegent.ac.annotation.Topic;
import cn.elegent.pay.ElegentPay;
import cn.elegent.pay.dto.RefundRequest;
import com.dkd.applet.common.config.TopicConfig;
import com.dkd.applet.common.constant.OrderStatus;
import com.dkd.applet.common.constant.PayStatus;
import com.dkd.applet.domain.Channel;
import com.dkd.applet.domain.Order;
import com.dkd.applet.domain.dto.VendoutResultDTO;
import com.dkd.applet.service.ChannelService;
import com.dkd.applet.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * 出货结果处理类
 */
@Topic(TopicConfig.VMS_RESULT_TOPIC)
@Slf4j
public class VendoutResultHandler implements ACHandler<VendoutResultDTO> {

    @Autowired
    private OrderService orderService;

    @Autowired
    private ElegentPay elegentPay;

    @Autowired
    private ChannelService channelService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void process(String s, VendoutResultDTO vendoutResultDTO) throws Exception {
        log.info("接收到出货结果,{}", vendoutResultDTO);

        Order order = orderService.getByOrderNo(vendoutResultDTO.getOrderNo());
        if (order == null) return;
        if (vendoutResultDTO.isSuccess()) {  //如果成功
            order.setStatus(OrderStatus.ORDER_STATUS_VENDOUT_SUCCESS);  //出货成功
            orderService.updateById(order);
            //扣减库存
            Channel channel = channelService.getChanneleByInnerCodeAndChannelCode(vendoutResultDTO.getInnerCode(), vendoutResultDTO.getChannelCode());
            channel.setCurrentCapacity(channel.getCurrentCapacity() - 1);
            channelService.updateById(channel);

        } else {
            order.setStatus(OrderStatus.ORDER_STATUS_VENDOUT_FAIL);//修改订单状态为失败
            order.setPayStatus(PayStatus.PAY_STATUS_REFUNDING);  //退款中
            orderService.updateById(order);
            RefundRequest refundRequest = new RefundRequest();
            refundRequest.setOrderSn(vendoutResultDTO.getOrderNo());//订单号
            refundRequest.setRequestNo(vendoutResultDTO.getOrderNo()); //退款号
            refundRequest.setTotalFee(order.getAmount());//金额
            refundRequest.setRefundAmount(order.getAmount());//退款金额
            elegentPay.refund(refundRequest, order.getPayType());//发起退款

        }
    }
}